<template>
  <div class="payment-result">
    <!-- 成功状态 -->
    <div v-if="resultType === 'success'" class="result-container success">
      <div class="result-icon">
        <el-icon><CircleCheck /></el-icon>
      </div>

      <h1 class="result-title">支付成功！</h1>

      <div class="result-info">
        <div class="info-card">
          <div class="info-item">
            <span class="label">挂号编号:</span>
            <span class="value">{{ paymentInfo.appointmentId }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付金额:</span>
            <span class="value amount">¥{{ paymentInfo.amount }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式:</span>
            <span class="value">{{ paymentMethodText }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付时间:</span>
            <span class="value">{{ paymentTime }}</span>
          </div>
        </div>
      </div>

      <!-- 挂号详情 -->
      <div class="appointment-details">
        <h3>挂号详情</h3>
        <div class="details-grid">
          <div class="detail-item">
            <span class="label">科室:</span>
            <span class="value">{{ appointmentInfo.department }}</span>
          </div>
          <div class="detail-item">
            <span class="label">医生:</span>
            <span class="value">{{ appointmentInfo.doctor }}</span>
          </div>
          <div class="detail-item">
            <span class="label">挂号时间:</span>
            <span class="value">{{ appointmentInfo.time }}</span>
          </div>
          <div class="detail-item">
            <span class="label">诊室:</span>
            <span class="value">{{ appointmentInfo.room }}</span>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="printReceipt" class="action-button">
          <el-icon><Printer /></el-icon>
          打印凭条
        </el-button>
        <el-button @click="sendSMS" class="action-button">
          <el-icon><Message /></el-icon>
          发送短信
        </el-button>
        <el-button @click="goHome" class="action-button">
          <el-icon><HomeFilled /></el-icon>
          返回首页
        </el-button>
      </div>

      <!-- 温馨提示 -->
      <div class="tips">
        <h4>温馨提示</h4>
        <ul>
          <li>请提前15分钟到达医院候诊</li>
          <li>就诊时请携带打印挂号单</li>
          <li>如需改期或取消挂号，请人工柜台操作</li>
          <li>如有疑问，请咨询导诊台或拨打服务热线</li>
        </ul>
      </div>
    </div>

    <!-- 失败状态 -->
    <div v-else class="result-container failed">
      <div class="result-icon">
        <el-icon><CircleClose /></el-icon>
      </div>

      <h1 class="result-title">支付失败</h1>

      <div class="error-message">
        <p>支付过程中出现问题，请重试或选择其他支付方式</p>
        <div class="error-code" v-if="paymentInfo.errorCode">
          错误代码: {{ paymentInfo.errorCode }}
        </div>
      </div>

      <div class="result-info">
        <div class="info-card">
          <div class="info-item">
            <span class="label">支付金额:</span>
            <span class="value amount">¥{{ paymentInfo.amount }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式:</span>
            <span class="value">{{ paymentMethodText }}</span>
          </div>
          <div class="info-item">
            <span class="label">失败时间:</span>
            <span class="value">{{ paymentTime }}</span>
          </div>
        </div>
      </div>

      <!-- 失败原因提示 -->
      <div class="failure-reasons">
        <h3>可能的原因：</h3>
        <ul>
          <li>网络连接不稳定</li>
          <li>账户余额不足</li>
          <li>支付密码错误</li>
          <li>银行系统维护中</li>
          <li>支付超时</li>
        </ul>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="primary" @click="retryPayment" class="action-button">
          <el-icon><Refresh /></el-icon>
          重新支付
        </el-button>
        <el-button @click="goHome" class="action-button">
          <el-icon><HomeFilled /></el-icon>
          返回首页
        </el-button>
      </div>

      <!-- 客服信息 -->
      <div class="customer-service">
        <h4>需要帮助？</h4>
        <p>如果您遇到问题，请联系我们的客服中心</p>
        <div class="contact-info">
          <div class="contact-item">
            <el-icon><Phone /></el-icon>
            服务热线: 400-123-4567
          </div>
          <div class="contact-item">
            <el-icon><Clock /></el-icon>
            服务时间: 8:00-22:00
          </div>
        </div>
      </div>
    </div>

    <!-- 打印凭条弹窗 -->
    <el-dialog
      v-model="showPrintDialog"
      title="挂号凭条"
      width="600px"
      :close-on-click-modal="false"
      center
    >
      <div class="receipt-container">
        <div class="receipt-header">
          <h3>医院挂号凭条</h3>
          <div class="hospital-info">
            <p>智医云联</p>
            <p>自助服务系统</p>
          </div>
        </div>

        <!-- 新增的条形码区域 -->
        <div class="barcode-section">
          <div class="barcode">
            <div class="barcode-placeholder">
              <span><Qrcode :qrUrlStr="qrCodeContent" /></span>
              <span>{{ paymentInfo.appointmentId }}</span>
            </div>
          </div>
        </div>

        <div class="receipt-content">
          <div class="receipt-section">
            <h4>患者信息</h4>
            <div class="info-grid">
              <div class="info-row">
                <span class="label">姓名：</span>
                <span class="value">{{ patientInfo.name || "张某某" }}</span>
              </div>
              <div class="info-row">
                <span class="label">医保卡号：</span>
                <span class="value">{{
                  patientInfo.insuranceCard
                    ? patientInfo.insuranceCard.substring(0, 3) +
                      "*".repeat(patientInfo.insuranceCard.length - 3)
                    : "YB20240012345".substring(0, 3) + "*".repeat(9)
                }}</span>
              </div>
              <div class="info-row">
                <span class="label">身份证号：</span>
                <span class="value">{{
                  patientInfo.idCard
                    ? patientInfo.idCard.substring(0, 3) +
                      "*".repeat(patientInfo.idCard.length - 3)
                    : "110101199001011234".substring(0, 3) + "*".repeat(15)
                }}</span>
              </div>
            </div>
          </div>

          <div class="receipt-section">
            <h4>挂号信息</h4>
            <div class="info-grid">
              <div class="info-row">
                <span class="label">挂号编号：</span>
                <span class="value">{{ paymentInfo.appointmentId }}</span>
              </div>
              <div class="info-row">
                <span class="label">科室：</span>
                <span class="value">{{ appointmentInfo.department }}</span>
              </div>
              <div class="info-row">
                <span class="label">医生：</span>
                <span class="value">{{ appointmentInfo.doctor }}</span>
              </div>
              <div class="info-row">
                <span class="label">挂号时间：</span>
                <span class="value">{{ appointmentInfo.time }}</span>
              </div>
              <div class="info-row">
                <span class="label">诊室：</span>
                <span class="value">{{ appointmentInfo.room }}</span>
              </div>
            </div>
          </div>

          <div class="receipt-section">
            <h4>费用信息</h4>
            <div class="info-grid">
              <div class="info-row">
                <span class="label">挂号费：</span>
                <span class="value">¥{{ originalAmount.toFixed(2) }}</span>
              </div>
              <div
                v-if="paymentMode === 'insurance' && !useInsurance"
                class="info-row"
              >
                <span class="label">医保报销：</span>
                <span class="value deduction"
                  >-¥{{ insuranceDeduction.toFixed(2) }}</span
                >
              </div>
              <div class="info-row total">
                <span class="label">实付金额：</span>
                <span class="value total-amount"
                  >¥{{ paymentInfo.amount }}</span
                >
              </div>
              <div class="info-row">
                <span class="label">支付方式：</span>
                <span class="value">{{ paymentMethodText }}</span>
              </div>
            </div>
          </div>

          <div class="receipt-section">
            <h4 class="validity-title">本次挂号当日有效！</h4>
            <div class="tips-content validity-info">
              <p>如需报销，请于10天内到窗口补打正式票据</p>
              <p>如需退费，请至人工窗口办理相关手续</p>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPrintDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmPrint" :loading="printing">
            <el-icon><Printer /></el-icon>
            确认打印
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage } from "element-plus";
import Qrcode from "@/components/qrcode/Qrcode.vue";

// 外部属性
const props = defineProps({
  resultType: {
    type: String,
    required: true,
    validator: (value) => ["success", "failed"].includes(value),
  },
  appointmentInfo: {
    type: Object,
    required: true,
  },
  paymentInfo: {
    type: Object,
    default: () => ({}),
  },
  // 添加挂号编号属性
  appointmentId: {
    type: String,
    default: "",
  },
});

// 打印相关数据
const showPrintDialog = ref(false);
const printing = ref(false);
const printTime = ref("");
// 二维码内容
const qrCodeContent = ref(""); //挂号编码赋值

// 患者信息（从localStorage获取）
const patientInfo = ref({});

// 费用计算
const originalAmount = computed(() => {
  return props.appointmentInfo.fee || 0;
});

// 修改医保报销金额计算，优先使用传递过来的值
const insuranceDeduction = computed(() => {
  // 如果从父组件传递了医保报销金额，直接使用
  if (props.appointmentInfo.insuranceDeduction) {
    return props.appointmentInfo.insuranceDeduction;
  }
  return 0;
});


// 支付模式和使用保险状态（从props中获取或设置默认值）
const paymentMode = computed(() => props.paymentMode || "insurance");
const useInsurance = computed(() => props.useInsurance || false);



const emit = defineEmits(["retry", "home"]);

// 支付方式映射
const paymentMethods = {
  alipay: "支付宝",
  wechat: "微信支付",
  digital: "数字人民币",
  medical: "职工医保",
};

const paymentTime = ref(new Date().toLocaleString("zh-CN"));
const paymentMethodText = computed(() => {
  return paymentMethods[props.paymentInfo.method] || "支付宝";
});

// 修改打印凭条方法
const printReceipt = () => {
  // 获取当前时间
  const now = new Date();
  printTime.value = now.toLocaleString("zh-CN");

  // 加载患者信息
  loadPatientInfo();
  // 加载二维码信息
  loadQRCodeInfo();

  showPrintDialog.value = true;
};

// 确认打印
const confirmPrint = () => {
  printing.value = true;

  // 模拟打印过程
  setTimeout(() => {
    printing.value = false;
    showPrintDialog.value = false;
    ElMessage.success("凭条打印成功，请到打印机处取件");
  }, 2000);
};

// 加载患者信息
const loadPatientInfo = () => {
  try {
    // 加载患者信息
    const patient = JSON.parse(localStorage.getItem("currentPatient"));

    if (patient) {
      patientInfo.value = patient;
    }
  } catch (error) {
    console.error("加载患者信息失败:", error);    
  }
};

// 加载二维码信息
const loadQRCodeInfo = () => {
  try {
    const appointmentId = props.paymentInfo.appointmentId || "";
    qrCodeContent.value = `${appointmentId}`;
  } catch (error) {
    console.error("加载二维码信息失败:", error);
  }
};

const sendSMS = () => {
  ElMessage.success("预约信息已发送到您的手机");
};

const retryPayment = () => {
  emit("retry");
};

const goHome = () => {
  emit("home");
};
</script>

<style lang="scss" scoped>
.payment-result {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.result-container {
  background: white;
  border-radius: 16px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  text-align: center;

  &.success {
    border: 1px solid #e1f3d8;
  }

  &.failed {
    border: 1px solid #fcd3d3;
  }
}

.result-icon {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto 24px;
  font-size: 40px;

  .success & {
    background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
    color: white;
  }

  .failed & {
    background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
    color: white;
  }
}

.result-title {
  color: #303133;
  font-size: 28px;
  font-weight: 600;
  margin-bottom: 24px;
}

.error-message {
  margin-bottom: 24px;

  p {
    color: #606266;
    margin: 0 0 12px 0;
    font-size: 16px;
  }

  .error-code {
    color: #909399;
    font-size: 14px;
    background: #f5f7fa;
    padding: 6px 12px;
    border-radius: 6px;
    display: inline-block;
  }
}

.result-info {
  margin-bottom: 24px;
}

.info-card {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 1px solid #e2e8f0;
  border-radius: 12px;
  padding: 24px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e2e8f0;

  &:last-child {
    border-bottom: none;
  }

  .label {
    color: #606266;
    font-weight: 500;
    font-size: 14px;
  }

  .value {
    color: #303133;
    font-weight: 600;
    font-size: 14px;

    &.amount {
      color: #f56c6c;
      font-size: 16px;
    }
  }
}

.appointment-details {
  margin-bottom: 24px;
  text-align: left;

  h3 {
    color: #303133;
    margin-bottom: 16px;
    text-align: center;
    font-size: 18px;
  }
}

.details-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  background: #f8fafc;
  padding: 20px;
  border-radius: 8px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 6px;

  .label {
    color: #909399;
    font-size: 13px;
    font-weight: 500;
  }

  .value {
    color: #303133;
    font-weight: 600;
    font-size: 14px;
  }
}

.failure-reasons {
  margin-bottom: 24px;
  text-align: left;
  background: #fef0f0;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #f56c6c;

  h3 {
    color: #f56c6c;
    margin: 0 0 12px 0;
    font-size: 16px;
  }

  ul {
    margin: 0;
    padding-left: 20px;
    color: #606266;

    li {
      margin-bottom: 6px;
      line-height: 1.5;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.action-buttons {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;

  .failed & {
    grid-template-columns: repeat(2, 1fr);
  }

  .action-button {
    height: 50px;
    font-size: 16px;
    font-weight: 500;
    border-radius: 12px;

    .el-icon {
      margin-right: 6px;
    }
  }
}

.tips {
  text-align: left;
  background: #fff6e6;
  padding: 20px;
  border-radius: 8px;
  border-left: 4px solid #e6a23c;

  h4 {
    color: #e6a23c;
    margin: 0 0 12px 0;
    font-size: 16px;
  }

  ul {
    margin: 0;
    padding-left: 20px;
    color: #606266;

    li {
      margin-bottom: 6px;
      line-height: 1.5;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.customer-service {
  text-align: center;
  background: #f5f7fa;
  padding: 24px;
  border-radius: 8px;

  h4 {
    color: #303133;
    margin: 0 0 8px 0;
    font-size: 16px;
  }

  p {
    color: #606266;
    margin: 0 0 16px 0;
  }
}

.contact-info {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.contact-item {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #606266;
  font-size: 14px;
  font-weight: 500;

  .el-icon {
    color: #3b82f6;
  }
}

/* 打印凭条样式 */
.receipt-container {
  width: 66.67%; // 新增，宽度为原来的三分之二
  margin: 0 auto; // 居中显示
  background: white;
  border: 2px solid #333;
  padding: 20px;
  font-family: "Courier New", monospace;
  max-height: 70vh;
  overflow-y: auto;
}

.receipt-header {
  text-align: center;
  border-bottom: 2px dashed #333;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.receipt-header h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: bold;
}

// 新增条形码区域样式
.barcode-section {
  text-align: center;
  margin: 15px 0;
  padding: 10px 0;
  border-bottom: 1px dashed #ccc;
}

.hospital-info {
  font-size: 14px;
}

.hospital-info p {
  margin: 2px 0;
}

.receipt-content {
  margin-bottom: 20px;
}

.receipt-section {
  margin-bottom: 20px;

  .validity-title {
    text-align: center;
    margin-bottom: 10px;
  }

  .validity-info {    
    line-height: 1.6;
  }

  .validity-info p {
    margin: 8px 0;
    font-size: 13px;
  }
}

.receipt-section h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ccc;
  padding-bottom: 5px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.info-row .label {
  font-weight: bold;
  min-width: 80px;
}

.info-row .value {
  text-align: right;
  flex: 1;
  margin-left: 10px;
}

.info-row.total {
  border-top: 1px solid #333;
  padding-top: 8px;
  margin-top: 8px;
  font-weight: bold;
}

.info-row .deduction {
  color: #67c23a;
}

.info-row .total-amount {
  color: #f56c6c;
  font-size: 16px;
}

.tips-content {
  font-size: 12px;
  line-height: 1.4;
}

.tips-content p {
  margin: 4px 0;
}

.receipt-footer {
  border-top: 2px dashed #333;
  padding-top: 15px;
  text-align: center;
}

.print-time {
  font-size: 12px;
  margin-bottom: 15px;
}

.barcode-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 5px;
}

.barcode-lines {
  width: 200px;
  height: 60px;
  background: repeating-linear-gradient(
    90deg,
    #000,
    #000 2px,
    transparent 2px,
    transparent 4px
  );
  border: 1px solid #ccc;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .payment-result {
    padding: 16px;
  }

  .result-container {
    padding: 24px;
  }

  .result-icon {
    width: 60px;
    height: 60px;
    font-size: 30px;
  }

  .result-title {
    font-size: 24px;
  }

  .details-grid {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    grid-template-columns: 1fr;

    .failed & {
      grid-template-columns: 1fr;
    }
  }

  .contact-info {
    grid-template-columns: 1fr;
  }

  .info-card {
    padding: 20px;
  }

  .receipt-container {
    padding: 15px;
  }

  .info-row {
    font-size: 12px;
  }

  .barcode-lines {
    width: 150px;
    height: 40px;
  }
}

@media (max-width: 480px) {
  .payment-result {
    padding: 12px;
  }

  .result-container {
    padding: 20px;
  }

  .result-title {
    font-size: 22px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;

    .value {
      align-self: flex-end;
    }
  }
}
</style>